package com.mi.rof.utils;

import com.mi.rof.entity.SystemException;
import com.mi.rof.entity.enums.ExceptionEnum;
import com.mi.rof.entity.vo.UserInfoVo;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;



import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {
    private static String jwtToken = "test@mi.com" ;
    private JwtUtils() {
    }

    public static String createToken(UserInfoVo userInfoVo) {
        Map<String, Object> claims = new HashMap<>(3);
        claims.put("userId", userInfoVo.getUserId());
        claims.put("username", userInfoVo.getUsername());
        claims.put("email", userInfoVo.getEmail());
        claims.put("phoneNumber", userInfoVo.getPhoneNumber());
        claims.put("userRole", userInfoVo.getUserRole());
        //真正设置过期时间
        JwtBuilder jwtBuilder = Jwts.builder()
                                .signWith(SignatureAlgorithm.HS256, jwtToken)
                                .setClaims(claims)
                                .setIssuedAt(new Date())
                                .setExpiration(new Date(System.currentTimeMillis() +  24 * 60 * 60 * 1000));
        return  jwtBuilder.compact();
    }


    public static Map<String, Object> checkToken(String token) {
        try {
            Jwt parse = Jwts.parser().setSigningKey(jwtToken).parseClaimsJws(token);
            return (Map<String, Object>) parse.getBody();
        } catch (Exception e) {
            throw  new SystemException(ExceptionEnum.TOKEN_EXPIRED.getCode(),
                    ExceptionEnum.TOKEN_EXPIRED.getMsg());
        }
    }

}
